import math

def possion(x, y):
    # for calculation the p-value in gene neighbor
    if x == 0:
        return math.pow(math.e, -1*y)
    else:
        return possion(x-1, y)*y/x


def Cm(n, x, N, M, e=1e-6):
    '''cumulative hypergeometric distribution
    say we have N white balls, M black balls,
    if i pick n balls, what's the possiblity i pick less than x black balls
    e is error
    result should less than 1
    '''
    def inv_jm(n, x, N, m):
        return (1-x/(m+1))/(1-(n-1-x)/(N-1-m))

    n = float(n)
    x = float(x)
    N = float(N)
    M = float(M)
    s = 1.0

    for k in xrange(int(x), int(M)-1):
        s = s * inv_jm(n, x, N, k) + 1.0

    ak = s
    bk = s
    k = M-2
    epsk = 2*e

    while k< (N-(n-x)-1) and epsk > e:
        ck = ak/bk
        k += 1
        jjm = inv_jm(n, x, N, k)
        bk = bk * jjm + 1.0
        ak = ak * jjm
        epsk = (N-(n-x)-1-k)*(ck-ak/bk)

    return 1-(ak/bk-epsk/2)




#END